package com.br.socket;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;
import org.apache.log4j.Logger;

import com.br.command.impl.Desconectar;

@WebServlet("/gamesocket")
public class GameSocket extends WebSocketServlet{

	private static final long serialVersionUID = 1L;
	
	private static Logger logger = Logger.getLogger(GameSocket.class);
    
    private static List<ConnectionWS> connections = new ArrayList<ConnectionWS>();
    
    /**
     * quando criar uma conexao
     */
    protected StreamInbound createWebSocketInbound(String subProtocol, HttpServletRequest request) {
        return new ConnectionWS();
    }
    
    /**
     * enviar uma mensagem para todos
     * @param message
     */
    public static void broadcast(String message, ConnectionWS me){
    	synchronized (connections) {
    		for (int i = 0; i < connections.size(); i++) {
    			ConnectionWS con = connections.get(i);
    			try {
                	//validar para nao notificar eu mesmo
                   if(!con.getId().equals(me.getId())){
                	   con.sendMessage(message);
                   }                
                } catch (IOException e) {
                	//tratar conexao fechada que ainda nao foi removida
                    if(e.getMessage().contains("closed")){
                    	new Desconectar().process(con, null);
                    }
                    logger.error("broadcast error", e);
                }
			}
		}
    }
    
    public static List<ConnectionWS> getConnections(){
        return connections;
    }
     
}
